package com.mlog.njyjy.ndop.monitor.collector.factory;

import com.mlog.njyjy.ndop.monitor.collector.dao.TaskRepository;
import com.mlog.njyjy.ndop.monitor.collector.exception.PdtScanException;
import com.mlog.njyjy.ndop.monitor.collector.route.BaseScanRoute;
import com.mlog.njyjy.ndop.monitor.collector.route.ScanRoute;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ServiceLoader;

/**
 * 扫描路由仓库
 *
 * @author zyz
 * @version v1.0, 2020/07/29
 */
@Slf4j
public class ScanRouteFactory {

    private List<ScanRoute> scanRouteList = new ArrayList<>(2);

    private TaskRepository taskRepository;

    public ScanRouteFactory(TaskRepository taskRepository) {
        this.taskRepository = taskRepository;
    }

    public void init() {
        ServiceLoader<ScanRoute> routes = ServiceLoader.load(ScanRoute.class);
        for (ScanRoute handler : routes) {
            scanRouteList.add(handler);
        }
        log.info("[scanRoute] loaded [{}] routes", scanRouteList.size());
    }

    /**
     * get route
     *
     * @param mode
     * @return
     */
    public ScanRoute get(String mode) {
        Optional<ScanRoute> opt = scanRouteList.stream().filter(route -> route.support(mode)).findFirst();
        if (opt.isPresent()) {
            ScanRoute route = opt.get();
            if (route instanceof BaseScanRoute) {
                ((BaseScanRoute) route).initialize(taskRepository);
            }
            return route;
        }
        throw new PdtScanException(String.format("not found route for mode [{%s}]", mode));
    }
}
